<?php
class MessagesController extends AppController {
	public $name = 'Messages';
	public $paginate = array();

	function beforeFilter() {
		$this->Auth->Authorize = 'controller';
		$this->Security->blackHoleCallback = 'blackhole';
	}

	function blackhole($type) {
		if($this->request->params['action'] == 'view' || $this->request->params['action'] == 'deleteSingle'){
			return true;
		}
		throw new MethodNotAllowedException(__('Nope: ' . $type . ' - ' . Router::url($this->here, true)));
	}

	public function isAuthorized($user) {
		return true;
	}

	public function index(){
		$this->set('title_for_layout', SITE_NAME . ' &bull; Private Messages');
		$this->paginate = array(
			'order' => 'Message.created DESC',
			'conditions' => array(
				'AND' => array(
					'Message.user_id' => $this->Auth->User('id'),
					'Message.to_user_id' => $this->Auth->User('id')
				)
			)
		);

		$messages = $this->paginate('Message');
		$this->set('unreadCount', (count($messages) > 0) ? $messages[0]['Unread']['message_count'] : 0);
		$this->set('messages', $messages);
	}

	public function sent(){
		$this->set('title_for_layout', SITE_NAME . ' &bull; Sent Messages');
		$this->paginate = array(
			'order' => 'Message.created DESC',
			'conditions' => array(
				'AND' => array(
					'Message.user_id' => $this->Auth->User('id'),
					'Message.from_user_id' => $this->Auth->User('id')
				)
			)
		);
		$messages = $this->paginate('Message');
		$this->set('messages', $messages);
	}

	public function view(){
		require_once(APP . 'Vendor' . DS . 'markdown'. DS .'markdown.php');
		$id = $this->request->data['messageId'];
		$this->autoRender = false;
		if($this->request->is('ajax')){
			$this->Message->id = $id;
			if($this->Message->exists() && $this->Message->isOwnedBy($id)){
				$this->Message->saveField('viewed', 0);

				$messageData = $this->Message->read();
				$body = Markdown($messageData['Message']['body']);
				return json_encode(array('status' => true, 'username' => $messageData['From']['username'], 'title' => Sanitize::html($messageData['Message']['title']), 'body' => $body));
			}
		}
		return json_encode(array('status' => false, 'title' => 'Nope', 'message' => 'Nope'));
	}

	public function send($id = null, $username = null){
		$this->set('title_for_layout', SITE_NAME . ' &bull; Compose');
		if($this->request->is('get')){

			$this->Message->id = $id;
			if($this->Message->exists() && $this->Message->isOwnedBy($id)){
				$messageData = $this->Message->read();
				$this->set($this->request->data[$this->Message->alias]['title'] = $messageData['Message']['title']);
				$body = '';
				foreach(explode(PHP_EOL, $messageData['Message']['body']) as $line){
					$body .= '> ' . $line . PHP_EOL;
				}
				$body = str_repeat(PHP_EOL, 4) . '> **' . $messageData['From']['username'] . ' wrote at ' . $messageData[$this->Message->alias]['created'] . '**' . PHP_EOL . '> ' . PHP_EOL . trim($body);
				$this->set($this->request->data[$this->Message->alias]['body'] = $body);
			}

			$this->set($this->request->data[$this->Message->alias]['to'] = $username);

		}
		if($this->request->is('post')){
			// send to recipient
			$this->request->data[$this->Message->alias]['from_user_id'] = $this->Auth->User('id');
			$this->request->data[$this->Message->alias]['to_user_id'] = $this->Message->User->field('id', array('username' => $this->request->data[$this->Message->alias]['to']));
			$this->request->data[$this->Message->alias]['user_id'] = $this->Message->User->field('id', array('username' => $this->request->data[$this->Message->alias]['to']));
			$this->Message->create();

			if($this->Message->save($this->request->data)){

				// check if email notifications are enabled and send email to recipient
				$userId = $this->Message->User->field('id', array('username' => $this->request->data[$this->Message->alias]['to']));
				$this->Message->User->id = $userId;
				$userData = $this->Message->User->read();

				if($userData['User']['message_alert'] == "1"){
					$email = new CakeEmail();
					$email->config('noreply');
					$email->template('message_alert');
					$email->viewVars(array('toUsername' => $userData['User']['username'], 'fromUsername' => $this->Auth->User('username')));
					$email->to($userData['User']['email']);
					$email->subject('New private message');
					$email->emailFormat('html');

					$email->send();
				}

				// send copy to sent messages
				$this->request->data[$this->Message->alias]['viewed'] = 0;
				$this->request->data[$this->Message->alias]['user_id'] = $this->Auth->User('id');
				$this->Message->create();
				if($this->Message->save($this->request->data)){
					$this->Session->setFlash('Your message has been sent', 'default', array('class' => 'success'));;
					$this->redirect(array('controller' => 'messages', 'action' => 'index'));
				}
			}
		}
	}


	public function deleteSingle(){
		$this->autoRender = false;
		if($this->request->is('ajax')){
			$messageId = $this->request->data['messageId'];
			$this->Message->id = $messageId;
			if($this->Message->exists() && $this->Message->isOwnedBy($messageId)){

				if($this->Message->delete()){
					return json_encode(array('status' => 'success', 'messageId' => $messageId));
				}
			}
		}
		return json_encode(array('notice' => 'no dice', 'messageId' => 0));
	}


	public function delete(){
		if($this->request->is('get')){
			throw new MethodNotAllowedException();
		}elseif($this->request->is('post')){
			$i = 0;
			foreach($this->request->data['Message']['selectedMessages'] AS $messageId){
				$this->Message->id = $messageId;
				if($this->Message->exists() && $this->Message->isOwnedBy($messageId)){
					if($this->Message->delete()){
						$i++;
					}
				}
			}
			$this->Session->setFlash($i . ': Messages have been deleted.', 'default', array('class' => 'success'));
			$this->redirect(array('action' => 'index'));
		}
	}
}